import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animation

from CpuUsageThread import get_cpu_usage

count = 0
df = pd.DataFrame()

fig = plt.figure()
ax = plt.axes()
line, = ax.plot([], [], label="Real Time", lw=1, linestyle='--')
line2, = ax.plot([], [], label="Avg", lw=2)
ax.legend(handles=[line, line2], loc='lower right')


def gen_data():
    global count
    count += 1
    # time_now = pd.to_datetime(pd.datetime.now())
    index = ['time', 'total_usage', 'app_1', 'app_2']
    data = [count, get_cpu_usage(), np.random.rand(), np.random.rand()]
    return pd.Series(data=data, index=index, name=count)


def update_data():
    global df
    df = df.append(gen_data())


def update(i):
    update_data()
    xdata = df['time']
    ydata = df['total_usage']
    line.set_data(xdata, ydata)
    # line.axes.relim()
    # line.axes.autoscale_view(True, True, True)
    line.axes.axis([xdata.min(), xdata.max(), ydata.min(), ydata.max()])

    y_move_avg = ydata.rolling(60, min_periods=1).mean()
    line2.set_data(xdata, y_move_avg)
    # plt.xticks(xdata)
    return line, line2


anim = animation.FuncAnimation(fig, update, frames=200, interval=1000, blit=False)

# df = df.append(gen_data())
# df = df.append(gen_data())
# df = df.append(gen_data())
# df = df.append(gen_data())
# df = df.append(gen_data())
# df.set_index(["time"], inplace=True)
plt.show()
